/*
 * @Author: your name
 * @Date: 2021-09-21 14:51:32
 * @LastEditTime: 2021-09-22 09:23:18
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \数据结构\队列\数组队列\queue.c
 */
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include "queue.h"

QUEUE * createQueue(int queueSize)
{
    if(queueSize <= 0){
        printf("queueSize Error\n");
        return NULL;
    }
    //申请队列空间
    QUEUE * q = (QUEUE*)malloc(sizeof(QUEUE));
    //No memory
    if(!q){
        printf("no memory\n");
        return NULL;
    }
    //申请队列数组空间,数组中有一个位置是空的,故至少多申请一个
    q->array = (QElemType*)malloc(sizeof(QElemType)*(queueSize+2));
    //no memory
    if(!q->array){
        printf("no memory\n");
        return NULL;
    }
    q->queueSize = queueSize;
    q->front = 0;
    q->rear = 0;
    return q;
}

bool freeQueue(QUEUE *q)
{
    if(q){
        if(q->array){
            free(q->array);
        }
        free(q);
    }
}

bool EnQueue(QUEUE *q, QElemType elem)
{
    if(isFull(q)){
        printf("queue full , Error\n");
        return false;
    }
    q->array[q->rear] = elem;
    q->rear = (q->rear + 1) % (q->queueSize + 1);
    return true;
}

QElemType DeQueue(QUEUE *q)
{
    if(isEmpty(q)){
        printf("queue empty , Error\n");
        exit(-1);
    }
    QElemType elem = q->array[q->front];
    q->front = (q->front + 1) % (q->queueSize + 1);
    return elem;
}

bool isEmpty(QUEUE *q)
{
    if(!q){
        printf("no queue\n");
        exit(-1);
    }
    if(q->front == q->rear){
        return true;
    }
    return false;
}

bool isFull(QUEUE *q)
{
    if(!q){
        printf("no queue\n");
        exit(-1);
    }
    if(((q->rear + 1) % (q->queueSize + 1)) == q->front){
        return true;
    }
    return false;
}

bool clearQueue(QUEUE *q)
{
    if(!q){
        printf("no queue\n");
        return false;
    }
    q->front = 0;
    q->rear = 0;
    return true;
}

int QueueLength(QUEUE *q)
{
    if(!q){
        printf("no queue\n");
        return -1;
    }
    return (q->rear - q->front + q->queueSize + 1) % (q->queueSize + 1);
}